<template>
  <div>
    <el-table :data="rows" border style="width: 100%">
      <el-table-column label="成交人类型" align="center">
        <template #default="{ row }">
          <el-select
            v-model="row.itemCategoryId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.businessName"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="区域" align="center">
        <template #default="{ row }">
          <el-select
            v-model="row.regionId"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="店面" align="center">
        <template #default="{ row }">
          <el-select
            v-model="row.storeId"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in row.storeArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="经纪人" align="center">
        <template #default="{ row }">
          <el-select
            v-model="row.workerId"
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in row.agentArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="分成比例 (%)" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.distributionRatio"
            :min="0"
            :max="100"
            @blur="getDistAmount(row)"
            controls-position="right"
          />
        </template>
      </el-table-column>

      <el-table-column label="分成金额 (元)" align="center">
        <template #default="{ row }">
          <el-input readonly v-model="row.distributionAmount" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="80px">
        <template #default="{ $index }">
          <el-button
            type="danger"
            icon="Delete"
            @click="removeRow($index)"
            size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="tips">
      <div>分成金额 = (买方服务费代收金额 + 卖方服务费代收金额) * 分成比例</div>
      <div>所有分成比例之和应为100%</div>
    </div>
    <!-- 添加按钮 -->
    <div class="add-btn">
      <el-button type="primary" plain icon="Plus" @click="addRow"
        >点击增加成交人</el-button
      >
    </div>
    <div class="actions" style="text-align: right">
      <el-button :loading="subLoad" type="primary" @click="submit"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from "vue";
import {
  listAllTransaction,
  listCompany,
  listStore,
  listWorker,
} from "@/api/business/tcForm";
import { editTcForm } from "@/api/business/tcForm";
import useHuazhongStore from "@/store/modules/huazhong";
const huazhongStore = useHuazhongStore();
const { proxy } = getCurrentInstance();
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  msgData: {
    type: Object,
    required: true,
  },
});
const emit = defineEmits(["update:data"]);

const rows = ref([...props.data]);
const initData = reactive({ ...props.msgData });
const fcMoney = ref("");
fcMoney.value = initData.serviceFeeProxySellerAr + initData.serviceFeeProxyBuyerAr;
function getDistAmount(row) {
  row.distributionAmount = fcMoney.value * (row.distributionRatio / 100);
}

// 同步更新到父组件
watch(rows, () => emit("update:data", rows.value), { deep: true });

const categoryOptions = ref([]);
const companyList = ref([]);
const fetchStoresAndAgents = async (regionId, row) => {
  // 获取门店列表
  const { data } = await listStore({ regionId });

  row.storeArr = data || [];
};
const fetchAgents = async (storeId, row) => {
  // 获取经纪人列表
  const { data } = await listWorker({ storeId });

  row.agentArr = data || [];
};
const setupRowWatch = (row) => {
  let isInitialized = false;
  watch(
    () => row.regionId,
    async (regionId, oldRegionId) => {
      if (!regionId) {
        row.storeArr = [];
        row.agentArr = [];
        row.storeId = "";
        row.workerId = "";
        return;
      }
      fetchStoresAndAgents(regionId, row);
      // ✅ 区别初始化和后续用户操作
      if (isInitialized && regionId !== oldRegionId) {
        row.storeId = "";
        row.workerId = "";
      }

      isInitialized = true;
    },
    { immediate: true }
  );
  let isInitializedWorker = false;
  watch(
    () => row.storeId,
    async (storeId, oldStoreId) => {
      if (!storeId) {
        row.agentArr = [];
        row.workerId = "";
        return;
      }
      fetchAgents(storeId, row);
      // ✅ 区别初始化和后续用户操作
      if (isInitializedWorker && storeId !== oldStoreId) {
        row.workerId = "";
      }

      isInitializedWorker = true;
    },
    { immediate: true }
  );
};
onMounted(() => {
  rows.value.forEach(setupRowWatch);

  listAllTransaction({ cateType: 3 }).then((res) => {
    categoryOptions.value = res.data;
  });

  listCompany().then((res) => {
    companyList.value = res.data;
  });
});

// 添加新成交人
const addRow = () => {
  const newRow = reactive({
    itemCategoryId: "",
    regionId: "",
    storeId: "",
    workerId: "",
    distributionRatio: 0,
    distributionAmount: "",
    storeArr: [],
    agentArr: [],
  });
  rows.value.push(newRow);
  setupRowWatch(newRow);
};

// 删除成交人
const removeRow = (index) => {
  rows.value.splice(index, 1);
};
const subLoad = ref(false);
const submit = () => {
  const data = rows.value.map((v) => {
    const { storeArr, agentArr, ...reset } = v;
    return reset;
  });
  const payload = {
    id: initData.id,
    sysHzRoomServiceFeeDistributionList: data,
  };
  //验证居间服务分成信息分成比例之和为100
  const cooperationCount = payload.sysHzRoomServiceFeeDistributionList.reduce(
    (n, v) => n + v.distributionRatio,
    0
  );
  const sysHz = huazhongStore.sysHzCommissionDistributionList;
  const sysHzCount = sysHz.reduce((n, v) => n + v.distributionRatio, 0);
  if (cooperationCount + sysHzCount != 100) {
    proxy.$modal.msgError("所有分成比例相加之和应该为100");
    return;
  }
  // if (cooperationCount != 100) {
  //   proxy.$modal.msgError("居间服务分成信息中所有分成比例相加之和应该为100");
  //   return;
  // }
  subLoad.value = true;
  // TODO: 调用接口提交
  editTcForm(payload)
    .then((res) => {
      subLoad.value = false;
      proxy.$modal.msgSuccess("修改成功");
    })
    .catch((err) => {
      subLoad.value = false;
    });
};
</script>

<style lang="scss" scoped>
.add-btn {
  margin-top: 10px;
  text-align: left;
}
.tips {
  font-size: 12px;
  color: #999;
  div {
    margin-top: 4px;
  }
}
</style>
